import pandas_datareader.data as web
import datetime
import time
from sklearn.preprocessing import StandardScaler
from collections import deque
import numpy as np
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import LSTM, Dense, Dropout
from sklearn.model_selection import train_test_split #划分数据集

start = datetime.datetime(2000, 1, 1)
end = datetime.datetime(2021, 9, 1)
df = web.DataReader('AAPL', 'stooq', start, end)
print(df)

#df.to_csv('./AAPL.csv', encoding='utf_8_sig')#通过输出发现没有无效值
df.dropna(inplace=True)#删掉空值
#df.to_csv('./AAPL_dropna.csv', encoding='utf_8_sig')#通过删除空值发现没有无效值
df.sort_index(inplace=True)
pre_day = 10
df['lable'] = df['Close'].shift(-pre_day)
print(df)

#先对数据进行标准化
scaler = StandardScaler()
print(df.iloc[:, : -1])
sca_X = scaler.fit_transform(df.iloc[:, : -1])
sca_X = scaler.fit_transform(df.iloc[:, : -1])
print(sca_X)

mem_his_days = 60
deq = deque(maxlen=mem_his_days)

X = []
for i in sca_X:
    deq.append(list(i))
    if len(deq)==mem_his_days:
        X.append(list(deq))
        #print(X)
        #break
X_lately = X[-pre_day:]
X = X[:-pre_day]
print(len(X))
print(len(X_lately))

y = df['lable'].values[mem_his_days-1: -pre_day]
print(len(y))
print(y)

X = np.array(X)
y = np.array(y)
print(X.shape)
print(y.shape)

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2)

model = Sequential()

#第1层
model.add(LSTM(500, input_shape=X.shape[1:], activation='relu', return_sequences=True))
model.add(Dropout(0.03, seed=int(time.time())))
#第2层
model.add(LSTM(400, activation='relu', return_sequences=True))
model.add(Dropout(0.02, seed=int(time.time())))
#第3层
model.add(LSTM(300, activation='relu', return_sequences=True))
model.add(Dropout(0.02, seed=int(time.time())))
#第4层
model.add(LSTM(200, activation='relu', return_sequences=True))
model.add(Dropout(0.02, seed=int(time.time())))
#第5层
model.add(LSTM(100, activation='relu', return_sequences=True))
model.add(Dropout(0.02, seed=int(time.time())))
#第6层
model.add(LSTM(50, activation='relu'))
model.add(Dropout(0.01, seed=int(time.time())))
#第7层
model.add(Dense(40, activation='relu'))
model.add(Dropout(0.01, seed=int(time.time())))
#第8层
model.add(Dense(30, activation='relu'))
model.add(Dropout(0.01, seed=int(time.time())))
#第9层
model.add(Dense(20, activation='relu'))
model.add(Dropout(0.01, seed=int(time.time())))
#第10层
model.add(Dense(10, activation='relu'))
model.add(Dropout(0.01, seed=int(time.time())))
#输出层
model.add(Dense(1))
#编译
model.compile(optimizer = 'adam', loss='mean_squared_error', metrics=['mape'])
#训练
model.fit(X_train, y_train, batch_size=32, epochs=500, validation_data=(X_test, y_test))


